package service

import (
	"context"
	"database/sql"

	"gitee.com/WisdomClassroom/core"
	"gitee.com/WisdomClassroom/core/models"
	"gitee.com/WisdomClassroom/core/protobufs/v1/pb"
	"gitee.com/WisdomClassroom/userInfo/glb"
	"google.golang.org/grpc/metadata"
	"gorm.io/gorm"
)

func (s *Service) UpdatePassword(ctx context.Context, request *pb.UpdatePasswordRequest) (*pb.UpdatePasswordResponse, error) {
	md, ok := metadata.FromIncomingContext(ctx)
	if !ok {
		glb.Logger.Error("no metadata")
	}
	token, err := core.UnpackTokenFromMetadata(md)
	if err != nil {
		return &pb.UpdatePasswordResponse{Status: &pb.ResponseStatus{
			Code: core.ResponseStatusCodeNotAuth, Message: err.Error(),
		}}, nil
	}

	if request.GetNewPasswordMD5() != request.GetVerifyNewPasswordMD5() {
		return &pb.UpdatePasswordResponse{Status: &pb.ResponseStatus{
			Code:    core.ResponseStatusCodeOtherError,
			Message: "两次输入的新密码不同",
		}}, nil
	}

	user := &models.User{AccountID: token.AccountID}

	err = glb.DB.Select("account_id").Take(user).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return &pb.UpdatePasswordResponse{Status: &pb.ResponseStatus{
				Code:    core.ResponseStatusCodeOtherError,
				Message: "用户不存在",
			}}, nil
		}
		glb.Logger.Error(err.Error())
		return updatePasswordRespSvrErr, nil
	}

	// 需要旧密码数据, 所以要先查询
	if !user.Check(request.GetOldPasswordMD5()) {
		return &pb.UpdatePasswordResponse{Status: &pb.ResponseStatus{
			Code:    core.ResponseStatusCodeNotAuth,
			Message: "旧密码错误",
		}}, nil
	}

	user.PasswordSalt = sql.NullString{String: user.GenSalt(), Valid: true}
	user.PasswordSSHA = sql.NullString{String: user.ComputePasswordSSHA(request.GetNewPasswordMD5()), Valid: true}
	err = glb.DB.Model(user).Updates(user).Error
	if err != nil {
		glb.Logger.Error(err.Error())
		return updatePasswordRespSvrErr, nil
	}

	return &pb.UpdatePasswordResponse{
		Status: &pb.ResponseStatus{Code: core.ResponseStatusCodeSuccess},
	}, nil
}
